package com.bauer.base.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CallableDemo {

    public static void main(String[] args) {
        demo1();
    }

    public static void demo1(){
        FutureTask<String> futureTask1 =  new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(10000);
                System.out.println("hha");
                return "futureTask1";
            }
        });

        FutureTask<String> futureTask2 =  new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "futureTask2";
            }
        });
        new Thread(futureTask1).start();
        new Thread(futureTask2).start();

        try {
            futureTask1.get(5,TimeUnit.SECONDS);
            System.out.println(futureTask1.get());
            System.out.println(futureTask2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static void demo2(){
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String>  future1 = threadPool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(10000);
                return "future1";
            }
        });
        System.out.println("finish");
        try {
            System.out.println(future1.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
    }

}
